//////////////////////////////////////////////////////////////////////////////
// Timer.cpp
// =========
// High Resolution Timer.
// This timer is able to measure the elapsed time with 1 micro-second accuracy
// in both Windows, Linux and Unix system 
//
//  AUTHOR: Song Ho Ahn (song.ahn@gmail.com)
// CREATED: 2003-01-13
// UPDATED: 2006-01-13
//
// Copyright (c) 2003 Song Ho Ahn//
//////////////////////////////////////////////////////////////////////////////
//	Modified for the klas engine.
//////////////////////////////////////////////////////////////////////////////

#include "../include/Timer.hpp"
using namespace klas;

Timer::Timer()
{
	/*#ifdef KLAS_WINDOWS
	QueryPerformanceFrequency(&m_frequency);
	m_startCount.QuadPart = 0;
	m_endCount.QuadPart = 0;
	#endif

	#ifdef KLAS_LINUX
	m_startCount.tv_sec = m_startCount.tv_usec = 0;
	m_endCount.tv_sec = m_endCount.tv_usec = 0;
	#endif

	m_stopped = true;
	m_startTimeInMicro = 0;
	m_endTimeInMicro = 0;*/
	
	m_startMilli = 0;
	m_endMilli = 0;
	restart();
}

Timer::~Timer()
{
}

void Timer::restart()
{
	m_stopped = false;
	m_startMilli = SDL_GetTicks();
	/*#ifdef KLAS_WINDOWS
  QueryPerformanceCounter(&m_startCount);
	#endif
	
	#ifdef KLAS_LINX
  gettimeofday(&m_startCount, NULL);
	#endif*/
}

void Timer::stop()
{
	m_stopped = true;
	m_endMilli = SDL_GetTicks();
	/*#ifdef KLAS_WINDOWS
	QueryPerformanceCounter(&m_endCount);
	#endif

	#ifdef KLAS_LINUX
	gettimeofday(&m_endCount, NULL);
	#endif*/
}

Real Timer::getSeconds()
{
	//return getMicroseconds() * 0.0000001;
	return (Real)getMilliseconds() * 0.001;
}

Uint32 Timer::getMilliseconds()
{
	if(m_stopped)
		return m_endMilli - m_startMilli;
	
	m_endMilli = SDL_GetTicks();
	
	return m_endMilli - m_startMilli;
}

/* FIXME: To high resolution for double */
/*long long Timer::getMicroseconds()
{
	#ifdef KLAS_WINDOWS
	if(m_stopped == false)
		QueryPerformanceCounter(&m_endCount);

	m_startTimeInMicro = m_startCount.QuadPart * (1000000.0 / m_frequency.QuadPart);
	m_endTimeInMicro = m_endCount.QuadPart * (1000000.0 / m_frequency.QuadPart);
	#endif
	
	#ifdef KLAS_LINUX
	if(m_stopped == false)
		gettimeofday(&m_endCount, NULL);

	m_startTimeInMicro = (m_startCount.tv_sec * 1000000.0) + m_startCount.tv_usec;
	m_endTimeInMicro = (m_endCount.tv_sec * 1000000.0) + m_endCount.tv_usec;
	#endif

	return m_endTimeInMicro - m_startTimeInMicro;
}*/
